<!DOCTYPE html>
<html lang="en">
<head>
    <meta charset="UTF-8">
    <meta http-equiv="X-UA-Compatible" content="IE=edge">
    <meta name="viewport" content="width=device-width, initial-scale=1.0">
    <title>栈操作</title>
</head>
<body>
    <script>
        function Stack(){
            //栈中的属性
            this.items = [];

            //栈的相关操作
            //1、将元素压入栈
            Stack.prototype.push = function(element){
                this.items.push(element)
            }
            //2、从栈中取出元素
            Stack.prototype.pop = function(){
                return this.items.pop()
            }
            //3、查看一下栈顶元素
            Stack.prototype.peek = function(){
                return this.items[this.items.length - 1]
            }
            //4、判断栈是否为空
            Stack.prototype.isEmpty = function(){
                return this.items.length===0
            }
            //5、获取栈中的元素
            Stack.prototype.size = function(){
                return this.items.length
            }
            //6、tostring()方法
            Stack.prototype.tostring = function(){
                var str = ''
                for(var i=0;i<this.items.length;i++) {
                    str+=this.items[i]+'';
                }
                return str;
            }
        }
        var sta=new Stack();
        sta.push(20)
        sta.push(10)
        sta.push(100)
        sta.push(88)
        console.log(sta)
        sta.pop()
        sta.pop()
        console.log('pop',sta)
        console.log('peek',sta.peek())
        console.log('isEmpty',sta.isEmpty())
        console.log('size',sta.size())
        console.log('tostring',sta.tostring())

        //十进制转2进制
        function dectobin(number) {
            //定义栈对象
            var stack=new Stack()
            while (number>0) {
                //获取余数放入栈中
                stack.push(number%2)
                //获取整数后的结果，作为下一次运行的结果
                number=Math.floor(number/2)
            }
            //从栈中取出0、1
            var str=''
            while (!stack.isEmpty()) {
                str+=stack.pop()
            }
            return str;
        }
        console.log(dectobin(10))
        console.log(dectobin(100))
        console.log(dectobin(1000))
    </script>
</body>
</html>